package com.bcbim.api_web.space_inventory_report.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bcbim.api_web.sys.interceptor.TranslateHandle;
import com.bcbim.authentication_interface.util.AuthUtil;
import com.bcbim.common.response.annotation.Translate;
import com.bcbim.common.response.vo.ReturnMsg;
import com.bcbim.common.response.vo.ReturnPageMsg;
import com.bcbim.common.sys.Code;
import com.bcbim.common.sys.Constant;
import com.bcbim.common.sys.ParamException;
import com.bcbim.common.sys.ReturnStatus;
import com.bcbim.common.util.GuidUtil;
import com.bcbim.common.util.ParamCheck;
import com.bcbim.operation_maintenance_interface.department.dto.DepartmentDTO;
import com.bcbim.operation_maintenance_interface.space_inventory_report.dao.SpaceInventoryReportDAO;
import com.bcbim.operation_maintenance_interface.space_inventory_report.dto.ListSpaceInventoryReportDTO;
import com.bcbim.operation_maintenance_interface.space_inventory_report.dto.ReportTableHeadDTO;
import com.bcbim.operation_maintenance_interface.space_inventory_report.dto.SpaceInventoryReportDTO;
import com.bcbim.operation_maintenance_interface.space_inventory_report.po.ExportSpaceInventoryReportPO;
import com.bcbim.operation_maintenance_interface.space_inventory_report.po.SaveSpaceInventoryReportPO;
import com.bcbim.operation_maintenance_interface.space_inventory_report.service.SpaceInventoryReportService;
import com.bcbim.operation_maintenance_interface.space_inventory_report.vo.ListSpaceInventoryReportNameVO;
import com.bcbim.operation_maintenance_interface.space_inventory_report.vo.ListSpaceInventoryReportVO;
import com.bcbim.operation_maintenance_interface.space_inventory_report.vo.TotalSpaceInventoryReportVO;
import com.bcbim.operation_maintenance_interface.space_inventory_report_table_head.dao.SpaceInventoryReportTableHeadDAO;
import com.bcbim.operation_maintenance_interface.space_inventory_report_table_head.service.SpaceInventoryReportTableHeadService;
import com.bcbim.operation_maintenance_interface.space_inventory_report_table_head.vo.SpaceInventoryReportTableHeadVO;
import com.bcbim.operation_maintenance_interface.space_type.dto.SpaceTypeDTO;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @version V 1.0.0
 * @Description：空间清册报表controller
 * @Author: haomeijie
 * @Date: 2022/4/13 16:06
 **/
@RestController
@RequestMapping("/spaceInventory")
public class SpaceInventoryReportController {
    @Reference(protocol = "dubbo", group = "spaceInventoryReport", version = "1.0.0")
    private SpaceInventoryReportService spaceInventoryReportServiceImpl;
    @Reference(protocol = "dubbo", group = "spaceInventoryReportTableHead", version = "1.0.0")
    private SpaceInventoryReportTableHeadService spaceInventoryReportTableHeadServiceImpl;
    @Value("${application.upload-path}")
    private String UPLOAD_PATH;

    /**
     * 空间清册列表
     *
     * @param reportPO
     * @return ReturnPageMsg
     * @Author: haomeijie
     * @Date: 2022/4/13 16:26
     */
    @RequestMapping("/list")
    @Translate
    public ReturnPageMsg list(ExportSpaceInventoryReportPO reportPO) {
        ListSpaceInventoryReportDTO reportDTO = JSONObject.parseObject(reportPO.getQuery(), ListSpaceInventoryReportDTO.class);
        reportDTO.setProjectId(reportPO.getProjectId());
        //参数校验
        try {
            ParamCheck.pageNumCheck(reportDTO.getPageNum(), reportDTO.getPageSize());
            ParamCheck.idCheck(reportDTO.getProjectId());
        } catch (ParamException e) {
            return ReturnPageMsg.consFail(ParamException.PARAMETER_ERROR);
        }
        //整理筛选条件
        if (StringUtils.isNotEmpty(reportDTO.getSpaceType())) {
            List<SpaceTypeDTO> typeDTOList = JSONObject.parseArray(reportDTO.getSpaceType(), SpaceTypeDTO.class);
            reportDTO.setSpaceTypeIds(typeDTOList);
        }
        if (StringUtils.isNotEmpty(reportDTO.getDepartment())) {
            List<DepartmentDTO> departmentDTOList = JSONObject.parseArray(reportDTO.getDepartment(), DepartmentDTO.class);
            reportDTO.setDepartmentIds(departmentDTOList);
        }
        //查询总数
        int total = spaceInventoryReportServiceImpl.listSpaceInventoryReportCount(reportDTO);
        List<ListSpaceInventoryReportVO> list = new ArrayList<>();
        if (total > 0) {
            reportDTO.setStart((reportDTO.getPageNum() - 1) * reportDTO.getPageSize());
            list = spaceInventoryReportServiceImpl.listSpaceInventoryReport(reportDTO);
        }
        return ReturnPageMsg.consSuccess(total, list);
    }

    /**
     * 导出空间清册列表
     *
     * @param reportPO
     * @return ReturnMsg
     * @Author: haomeijie
     * @Date: 2022/4/13 18:13
     */
    @RequestMapping("/export")
    public ReturnMsg export(ExportSpaceInventoryReportPO reportPO) {
        ListSpaceInventoryReportDTO reportDTO = JSONObject.parseObject(reportPO.getQuery(), ListSpaceInventoryReportDTO.class);
        reportDTO.setProjectId(reportPO.getProjectId());
        //整理筛选条件
        if (StringUtils.isNotEmpty(reportDTO.getSpaceType())) {
            List<SpaceTypeDTO> typeDTOList = JSONObject.parseArray(reportDTO.getSpaceType(), SpaceTypeDTO.class);
            reportDTO.setSpaceTypeIds(typeDTOList);
        }
        if (StringUtils.isNotEmpty(reportDTO.getDepartment())) {
            List<DepartmentDTO> departmentDTOList = JSONObject.parseArray(reportDTO.getDepartment(), DepartmentDTO.class);
            reportDTO.setDepartmentIds(departmentDTOList);
        }
        List<ReportTableHeadDTO> headList = JSONObject.parseArray(reportPO.getTableHead(), ReportTableHeadDTO.class);
        List<ListSpaceInventoryReportVO> list = spaceInventoryReportServiceImpl.listSpaceInventoryReport(reportDTO);
        TranslateHandle.translationData(list);
        String path = spaceInventoryReportServiceImpl.exportSpaceInventoryReport(list, headList, UPLOAD_PATH);
        if (StringUtils.isNotEmpty(path)) {
            return ReturnMsg.newInstance().setData(path).setStatus(ReturnStatus.SUCCESS.getCode());
        }
        return ReturnMsg.consFail("导出失败！");
    }

    /**
     * @Description: 空间清册 - 报表名称列表
     * @Date: 2022/4/14 11:26
     * @Param: [query]
     * @return: com.bcbim.common.response.vo.ReturnPageMsg
     * @Author: lihonggang
     **/
    @RequestMapping("/listSpaceInventoryReportName")
    public ReturnPageMsg listSpaceInventoryReportName(SpaceInventoryReportDTO query) {
        //参数校验
        try {
            ParamCheck.idCheck(query.getProjectId());
        } catch (ParamException e) {
            return ReturnPageMsg.consFail(ParamException.PARAMETER_ERROR);
        }
        //获取用户id
        String userId = AuthUtil.getUserIdDecrypt();
        //整理参数
        query.setUserId(userId);
        //查询空间清册报表名称列表总数
        int total = spaceInventoryReportServiceImpl.countListSpaceInventoryReportName(query);
        if (total == 0) {
            return ReturnPageMsg.consSuccess(total, Lists.newArrayList());
        }
        List<ListSpaceInventoryReportNameVO> list = spaceInventoryReportServiceImpl.listSpaceInventoryReportName(query);
        return ReturnPageMsg.consSuccess(total, list);
    }

    /**
     * @Description: 修改空间清册报表名称
     * @Date: 2022/4/14 14:47
     * @Param: [spaceInventoryReportDAO]
     * @return: com.bcbim.common.response.vo.ReturnMsg
     * @Author: lihonggang
     **/
    @RequestMapping("/updateSpaceInventoryReportName")
    public ReturnMsg updateSpaceInventoryReportName(SpaceInventoryReportDAO spaceInventoryReportDAO) {
        //参数校验
        try {
            ParamCheck.idCheck(spaceInventoryReportDAO.getId());
            ParamCheck.stringNotEmpty(spaceInventoryReportDAO.getReportName(), 50);
        } catch (ParamException e) {
            return ReturnMsg.consFail(ParamException.PARAMETER_ERROR);
        }
        spaceInventoryReportDAO.setUserId(AuthUtil.getUserIdDecrypt());
        boolean b = spaceInventoryReportServiceImpl.checkReportName(spaceInventoryReportDAO);
        if (b) {
            return ReturnMsg.consFail("空间清册报表名称重复！");
        }
        //整理空间清册报表参数
        spaceInventoryReportDAO.setUpdateBy(AuthUtil.getUserIdDecrypt());
        spaceInventoryReportDAO.setUpdateTime(LocalDateTime.now());

        int res = spaceInventoryReportServiceImpl.updateSpaceInventoryReportName(spaceInventoryReportDAO);
        return res == 1 ? ReturnMsg.consSuccess(Constant.SAVE_SUCCESS) : ReturnMsg.consFail(Constant.SAVE_FAIL);
    }

    /**
     * 查询表头设置
     *
     * @param spaceInventoryReportId 清册id
     * @return ReturnMsg
     * @Author: haomeijie
     * @Date: 2022/4/14 14:37
     */
    @RequestMapping("/listTableHead")
    public ReturnMsg listTableHead(String spaceInventoryReportId) {
        //参数校验
        try {
            ParamCheck.idCanBeEmpty(spaceInventoryReportId);
        } catch (ParamException e) {
            return ReturnMsg.consFail(ParamException.PARAMETER_ERROR);
        }
        if (StringUtils.isBlank(spaceInventoryReportId)) {
            spaceInventoryReportId = null;
        }
        List<SpaceInventoryReportTableHeadVO> list = spaceInventoryReportTableHeadServiceImpl.listTableHead(spaceInventoryReportId);
        return ReturnMsg.consSuccess(list);
    }

    /**
     * @Description: 删除空间清册报表名称
     * @Date: 2022/4/14 15:04
     * @Param: [spaceInventoryReportDAO]
     * @return: com.bcbim.common.response.vo.ReturnMsg
     * @Author: lihonggang
     **/
    @RequestMapping("/deleteSpaceInventoryReportName")
    public ReturnMsg deleteSpaceInventoryReportName(SpaceInventoryReportDAO spaceInventoryReportDAO) {
        //参数校验
        try {
            ParamCheck.idCheck(spaceInventoryReportDAO.getId());
        } catch (ParamException e) {
            return ReturnMsg.consFail(ParamException.PARAMETER_ERROR);
        }
        //整理空间清册报表参数
        spaceInventoryReportDAO.setUpdateBy(AuthUtil.getUserIdDecrypt());
        spaceInventoryReportDAO.setUpdateTime(LocalDateTime.now());
        spaceInventoryReportDAO.setDel(Constant.DEL);

        int res = spaceInventoryReportServiceImpl.updateSpaceInventoryReportName(spaceInventoryReportDAO);
        return res == 1 ? ReturnMsg.consSuccess(Constant.DEL_SUCCESS) : ReturnMsg.consFail(Constant.DEL_FAIL);
    }

    /**
     * 保存/另存为清册
     *
     * @param spaceInventoryReportPO
     * @return ReturnMsg
     * @Author: haomeijie
     * @Date: 2022/4/15 11:15
     */
    @RequestMapping("/saveReport")
    public ReturnMsg saveReport(SaveSpaceInventoryReportPO spaceInventoryReportPO) {
        //参数校验
        try {
            ParamCheck.stringNotEmpty(spaceInventoryReportPO.getReportName(), 50);
            ParamCheck.idCanBeEmpty(spaceInventoryReportPO.getId());
            ParamCheck.idCheck(spaceInventoryReportPO.getProjectId());
        } catch (ParamException e) {
            return ReturnMsg.consFail(ParamException.PARAMETER_ERROR);
        }
        //解析筛选条件
        ListSpaceInventoryReportDTO reportDTO = JSONObject.parseObject(spaceInventoryReportPO.getQuery(), ListSpaceInventoryReportDTO.class);
        //整理筛选条件
        if (StringUtils.isNotEmpty(reportDTO.getSpaceType())) {
            List<SpaceTypeDTO> typeDTOList = JSONObject.parseArray(reportDTO.getSpaceType(), SpaceTypeDTO.class);
            reportDTO.setSpaceTypeIds(typeDTOList);
        }
        if (StringUtils.isNotEmpty(reportDTO.getDepartment())) {
            List<DepartmentDTO> departmentDTOList = JSONObject.parseArray(reportDTO.getDepartment(), DepartmentDTO.class);
            reportDTO.setDepartmentIds(departmentDTOList);
        }
        //解析表头设置
        List<SpaceInventoryReportTableHeadDAO> headList = JSONObject.parseArray(spaceInventoryReportPO.getTableHead(), SpaceInventoryReportTableHeadDAO.class);

        //报表名称重复判断
        SpaceInventoryReportDAO spaceInventoryReportDAO = new SpaceInventoryReportDAO();
        spaceInventoryReportDAO.setId(spaceInventoryReportPO.getId());
        spaceInventoryReportDAO.setReportName(spaceInventoryReportPO.getReportName());
        spaceInventoryReportDAO.setUserId(AuthUtil.getUserIdDecrypt());
        spaceInventoryReportDAO.setProjectId(spaceInventoryReportPO.getProjectId());
        boolean b = spaceInventoryReportServiceImpl.checkReportName(spaceInventoryReportDAO);
        if (b) {
            return ReturnMsg.consFail("空间清册报表名称重复！");
        }
        int i = 0;
        if (StringUtils.isNotEmpty(spaceInventoryReportPO.getId())) {
            i = spaceInventoryReportServiceImpl.updateSpaceInventoryReport(spaceInventoryReportDAO, reportDTO, headList);
            return i > 0 ? ReturnMsg.newInstance().setStatus(ReturnStatus.SUCCESS.getCode())
                    .setData(spaceInventoryReportDAO.getId()).setMsg(Constant.SAVE_SUCCESS) : ReturnMsg.consFail(Constant.SAVE_FAIL);
        }
        //整理清册报表参数
        spaceInventoryReportDAO.setId(GuidUtil.get())
                .setCreateBy(AuthUtil.getUserIdDecrypt())
                .setCreateTime(LocalDateTime.now())
                .setDel(Constant.NOT_DEL);
        i = spaceInventoryReportServiceImpl.insertSpaceInventoryReport(spaceInventoryReportDAO, reportDTO, headList);
        return i > 0 ? ReturnMsg.newInstance().setStatus(ReturnStatus.SUCCESS.getCode())
                .setData(spaceInventoryReportDAO.getId()).setMsg(Constant.SAVE_SUCCESS) : ReturnMsg.consFail(Constant.SAVE_FAIL);
    }

    /**
     * 获取清册筛选条件
     *
     * @param spaceInventoryReportId
     * @return ReturnMsg
     * @Author: haomeijie
     * @Date: 2022/4/15 11:24
     */
    @RequestMapping("/listQuery")
    public ReturnMsg listQuery(String spaceInventoryReportId) {
        //参数校验
        try {
            ParamCheck.idCanBeEmpty(spaceInventoryReportId);
        } catch (ParamException e) {
            return ReturnMsg.consFail(ParamException.PARAMETER_ERROR);
        }
        if (StringUtils.isBlank(spaceInventoryReportId)) {
            spaceInventoryReportId = null;
        }
        List<Code> list = spaceInventoryReportServiceImpl.listQuery(spaceInventoryReportId);
        //将结果整理
        Map<String, Object> map = new HashMap<>();
        list.forEach(code -> {
            if (code.getCode().equals("floorIds")) {
                String[] ids = null;
                if (StringUtils.isNotEmpty(code.getValue())) {
                    ids = code.getValue().split(",");
                    for (int i = 0; i < ids.length; i++) {
                        ids[i] = ids[i].trim();
                    }
                }
                map.put(code.getCode(), ids);
            } else if (code.getCode().equals("topCategory")) {
                String[] top = null;
                if (StringUtils.isNotEmpty(code.getValue())) {
                    top = code.getValue().split(",");
                    for (int i = 0; i < top.length; i++) {
                        top[i] = top[i].trim();
                    }
                }
                map.put(code.getCode(), top);
            } else {
                map.put(code.getCode(), code.getValue());
            }

        });
        String json = JSON.toJSONString(map);
        ListSpaceInventoryReportDTO reportDTO = JSONObject.parseObject(json, ListSpaceInventoryReportDTO.class);
        return ReturnMsg.consSuccess(reportDTO);
    }

    /**
     * 复制报表
     *
     * @param reportNameVO
     * @return ReturnMsg
     * @Author: haomeijie
     * @Date: 2022/4/15 15:57
     */
    @RequestMapping("/copyReport")
    public ReturnMsg copyReport(ListSpaceInventoryReportNameVO reportNameVO) {
        //参数校验
        try {
            ParamCheck.idCheck(reportNameVO.getId());
        } catch (ParamException e) {
            return ReturnMsg.consFail(ParamException.PARAMETER_ERROR);
        }
        //获取同系列的报表名称
        List<String> list = spaceInventoryReportServiceImpl.listReportName(reportNameVO.getReportName(), reportNameVO.getProjectId());
        int i = 1;
        boolean b = true;
        String reportName = null;
        //进行名字复制
        while (b) {
            reportName = reportNameVO.getReportName() + "(" + i + ")";
            String finalReportName = reportName;
            b = list.stream().anyMatch(item -> item.equals(finalReportName));
            i++;
        }
        //判断报表名字是否超长
        try {
            ParamCheck.stringNotEmpty(reportName, 50);
        } catch (ParamException e) {
            return ReturnMsg.consFail("空间清册报表名称超长无法复制！");
        }
        //整理报表数据
        SpaceInventoryReportDAO spaceInventoryReportDAO = new SpaceInventoryReportDAO();
        spaceInventoryReportDAO.setId(GuidUtil.get())
                .setReportName(reportName)
                .setProjectId(reportNameVO.getProjectId())
                .setUserId(AuthUtil.getUserIdDecrypt())
                .setCreateBy(AuthUtil.getUserIdDecrypt())
                .setCreateTime(LocalDateTime.now())
                .setDel(Constant.NOT_DEL);
        //获取查询条件信息
        List<Code> query = spaceInventoryReportServiceImpl.listQuery(reportNameVO.getId());
        //获取表头数据
        List<SpaceInventoryReportTableHeadVO> head = spaceInventoryReportTableHeadServiceImpl.listTableHead(reportNameVO.getId());
        int j = spaceInventoryReportServiceImpl.copySpaceInventoryReport(spaceInventoryReportDAO, query, head);
        return j > 0 ? ReturnMsg.consSuccess(Constant.SAVE_SUCCESS) : ReturnMsg.consFail(Constant.SAVE_FAIL);
    }


    /**
     * 空间清册列表总计
     *
     * @param reportPO
     * @return ReturnMsg
     * @Author: haomeijie
     * @Date: 2022/4/19 17:53
     */
    @RequestMapping("/getTotal")
    public ReturnMsg getTotal(ExportSpaceInventoryReportPO reportPO) {
        try {
            ParamCheck.idCheck(reportPO.getProjectId());
        } catch (ParamException e) {
            return ReturnMsg.consFail(ParamException.PARAMETER_ERROR);
        }
        ListSpaceInventoryReportDTO reportDTO = JSONObject.parseObject(reportPO.getQuery(), ListSpaceInventoryReportDTO.class);
        //整理筛选条件
        if (StringUtils.isNotEmpty(reportDTO.getSpaceType())) {
            List<SpaceTypeDTO> typeDTOList = JSONObject.parseArray(reportDTO.getSpaceType(), SpaceTypeDTO.class);
            reportDTO.setSpaceTypeIds(typeDTOList);
        }
        if (StringUtils.isNotEmpty(reportDTO.getDepartment())) {
            List<DepartmentDTO> departmentDTOList = JSONObject.parseArray(reportDTO.getDepartment(), DepartmentDTO.class);
            reportDTO.setDepartmentIds(departmentDTOList);
        }
        reportDTO.setProjectId(reportPO.getProjectId());
        TotalSpaceInventoryReportVO total = spaceInventoryReportServiceImpl.getTotal(reportDTO);
        return ReturnMsg.consSuccess(total);
    }

}
